// 定义vuex

import vue from 'vue'
import Vuex from 'vuex'
import { loging } from '@/api/user'
import { Toast } from 'vant'
import router from '@/router'
import createPersistedState from 'vuex-persistedstate'
import user from './user'
import cart from './cart'
vue.use(Vuex)

// 数据
const state = {
  token: '',
  userInfo: 'hello vuex'
}
// Actions 异步操作的地方
const actions = {
  async GET_TOKEN({ commit }, t) {
    console.log(1111)
    // commit('SET_TOKEN', t)
    const { data } = await loging(t)
    console.log(data)
    if (data.code != 200) {
      Toast(data.msg)
    } else {
      const token = data.data.remember_token
      console.log(token)
      // localStorage.setItem('token', JSON.stringify(token))
      // localStorage.setItem('data', JSON.stringify(data))
      commit('SET_TOKEN', token)

      router.push('/my')
    }
  },
  GET_USERINFO({ commit }) {
    setTimeout(() => {
      const v = 'hello js'
      commit('SET_USERINFO', v)
    }, 1000)
  }

}

// mutations 同步修改state数据的地方
const mutations = {
  SET_TOKEN(state, t) {
    state.token = t
  },
  SET_USERINFO(state, t) {
    state.userInfo = t
  },
  REMOVE_TOKEN(state) {
    state.token = ''
    router.go(-1)
  }
}

// getters 相当于vue组件的computed， data
const getters = {
  count_userInfo(state) {
    return state.userInfo + '!'
  },
  count_token(state) {
    if (state.token) {
      return 'Bearer ' + state.token
    }
    return ''
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  getters,
  modules: {
    user,
    cart
  },
  plugins: [createPersistedState({
    storage: sessionStorage,
    key: 'token'
  })]//
})

